#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <set>

using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *slow = head, *fast = head;
        while(n> 0 && fast){ n--; fast = fast->next;}
        ////cout << n << endl;
        if (!fast && n > 0) return head;
        else if (!fast && n == 0) return head->next;
        while (fast->next) {
           slow = slow->next;
           fast = fast->next;
        }
        slow->next = slow->next->next;
        return head;
    }
};

//add better code
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *slow = head, *fast = head;
        while(n--> 0 && fast) fast = fast->next;
        if (n > 0) return head;  //less than n elemens;
        if (fast == NULL) return slow->next;
        while (fast->next != NULL) {
            slow = slow->next;
            fast = fast->next;
        }   
        slow->next = slow->next->next;
        return head;
    }   



ListNode *newList(int data[], int index, int size)
{
    ListNode *node = NULL;
    if (index == size)
        return node;

    node = new ListNode(data[index]);
    node->next = newList(data, index+1, size);

    return node;
}

//test on 1337 online judge and pass all the test
int main(int argc, char **argv)
{

    Solution mySolution;
    cout << "-----------------Test 1--------------------" << endl;
    int data[] = {1,4,5,6,7};
    ListNode *list1, *list2;
    list1 = newList(data, 0, sizeof(data)/sizeof(int));
    ListNode *list = mySolution.removeNthFromEnd(list1, 5);
    while(list) {
        cout << list->val << " ";
        list= list->next;
    }
    cout << endl;
    cout << "-----------------Test 2--------------------" << endl;
    ListNode *list_t = mySolution.removeNthFromEnd(list1, 6);
    while(list_t) {
        cout << list_t->val << " ";
        list_t= list_t->next;
    }
    cout << endl;

    cout << "-----------------Test 3--------------------" << endl;


    cout << "-----------------Test 4--------------------" << endl;


    cout << "-----------------Test 5--------------------" << endl;



}
